/*
Simple Forum Auto Poster.
Copyright (C) 2011 Gianni Van Hoecke.

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
package gui;

import domain.DomainController;
import domain.enums.View;
import domain.forumdata.Category;
import domain.forumdata.Post;
import domain.settings.Settings;
import domain.ui.UI;
import gui.help.about.AboutPanel;
import gui.history.HistoryContainer;
import gui.log.LoggingPanel;
import gui.menu.MenuBar;
import gui.posting.LinksFrame;
import gui.posting.PostingPanel;
import gui.result.PostResultContainerFrame;
import gui.settings.SettingsPanel;
import java.awt.Component;
import java.awt.Toolkit;
import java.io.File;
import java.net.URL;
import java.util.List;
import java.util.logging.Level;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import persistence.OpenBrowser;
import persistence.PersistenceController;

/**
 *
 * @author Gianni Van Hoecke <gianni.vh@gmail.com>
 */
public class PanelContainer extends javax.swing.JFrame implements UI {

    private AboutPanel aboutPanel;
    private PostingPanel postingPanel;
    private SettingsPanel settingsPanel;
    private LoggingPanel loggingPanel;
    private HistoryContainer historyContainer;

    private DefaultListModel listModel;
    private DefaultComboBoxModel comboModel;

    /** Creates new form PanelContainer */
    public PanelContainer()
    {
        initComponents();
        DomainController.getInstance().addObserver(this);
        initGUI();
        System.out.println("PanelContainer--> Constructor PanelContainer() gestart");
    }

    public void loadMenuBar()
    {
    	System.out.println("PanelContainer--> loadMenuBar() wordt gestart");
        this.setJMenuBar(MenuBar.getMenuBar());
        this.validate(); //or else the menu bar will become unresponsive.
    }

    void initGUI()
    {
    	System.out.println("PanelContainer--> initGUI() wordt gestart");
        this.setTitle(Settings.APP_NAME);
        this.setIconImage(Toolkit.getDefaultToolkit().getImage("/data/icon.png"));

        this.aboutPanel = new AboutPanel();
        this.postingPanel = new PostingPanel();
        this.settingsPanel = new SettingsPanel();
        this.loggingPanel = new LoggingPanel();
        this.historyContainer = new HistoryContainer();
        System.out.println("Deze komt uit package gui --> methode intiGUI");
        //***
        //TABS
        //***
        this.tabs.add("Post", this.postingPanel);
        this.tabs.add("Settings", this.settingsPanel);
        this.tabs.add("History", this.historyContainer);
        this.tabs.add("Log", this.loggingPanel);
        this.tabs.add("About", this.aboutPanel);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
    	System.out.println("PanelContainer--> initComponents() wordt gestart");
        tabs = new javax.swing.JTabbedPane();
        statusPanel1 = new gui.status.StatusPanel();
        forumQueuePane = new javax.swing.JSplitPane();
        forumsPanel1 = new gui.forums.ForumsPanel();
        queuePanel1 = new gui.queue.QueuePanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(800, 600));
        getContentPane().add(tabs, java.awt.BorderLayout.CENTER);
        getContentPane().add(statusPanel1, java.awt.BorderLayout.PAGE_END);

        forumQueuePane.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        forumQueuePane.setDividerLocation(350);
        forumQueuePane.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
        forumQueuePane.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        forumQueuePane.setLeftComponent(forumsPanel1);
        forumQueuePane.setRightComponent(queuePanel1);

        getContentPane().add(forumQueuePane, java.awt.BorderLayout.LINE_START);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JSplitPane forumQueuePane;
    private gui.forums.ForumsPanel forumsPanel1;
    private gui.queue.QueuePanel queuePanel1;
    private gui.status.StatusPanel statusPanel1;
    private javax.swing.JTabbedPane tabs;
    // End of variables declaration//GEN-END:variables

    public String getLog()
    {
    	System.out.println("PanelContainer--> getLog() wordt gestart");
        return this.loggingPanel.getLog();
    }

    public void loadCategories()
    {
    	System.out.println("PanelContainer--> loadCategories() wordt gestart");
        this.listModel = new DefaultListModel();
        this.comboModel = new DefaultComboBoxModel();
        
        for(Category cat : DomainController.getInstance().getCategories().getCategories())
        {
            this.listModel.addElement(cat.getName());
            this.comboModel.addElement(cat.getName());
        }

        this.settingsPanel.loadCategories(this.listModel);
        this.postingPanel.loadCategories(this.comboModel);
    }

    public void fireInformationMessage(String message, String title)
    {
    	System.out.println("PanelContainer--> fireInformationMessage() wordt gestart");
        JOptionPane.showMessageDialog(this, message, title, JOptionPane.INFORMATION_MESSAGE);
    }

    public String getSelectedCategory()
    {
    	System.out.println("PanelContainer--> getSelectedCategory() wordt gestart");
        return this.settingsPanel.getSelectedCategory();
    }

    public void loadForums()
    {
    	System.out.println("PanelContainer--> loadForums() wordt gestart");
        this.listModel = new DefaultListModel();
        this.forumsPanel1.loadForums();
    }

    public void loadHistory(List<Post> historyList)
    {
    	System.out.println("PanelContainer--> loadHistory() wordt gestart");
        this.historyContainer.loadHistory(historyList);
    }

    public String[] getSelectedForums()
    {
    	System.out.println("PanelContainer--> getSelectedForums() wordt gestart");
        return this.forumsPanel1.getSelectedForums();
    }

    public void postNewTopic()
    {
    	System.out.println("PanelContainer--> postNewTopic() wordt gestart");
        this.postingPanel.postNewTopic();
    }

    public void previewNewTopic()
    {
    	System.out.println("PanelContainer--> previewNewTopic() wordt gestart");
        this.postingPanel.previewNewTopic();
    }

    public void updateProcess(int progress, String status)
    {
    	System.out.println("PanelContainer--> updateProcess() wordt gestart");
        this.statusPanel1.updateProcess(progress, status);
    }

    public void setButtonsEnabled(boolean enabled)
    {
    	System.out.println("PanelContainer--> setButtonsEnabled() wordt gestart");
        for(Component c : this.getJMenuBar().getComponents())
        {
        	System.out.println("PanelContainer--> forlus --> setButtonsEnabled() wordt gestart");
            c.setEnabled(enabled);
        }

        this.postingPanel.setButtonsEnabled(enabled);
        this.forumsPanel1.setButtonsEnabled(enabled);
        this.queuePanel1.setButtonsEnabled(enabled);
        this.settingsPanel.setButtonsEnabled(enabled);
        this.loggingPanel.setButtonsEnabled(enabled);
        this.historyContainer.setButtonsEnabled(enabled);
    }

    public void fireDone()
    {
    	System.out.println("PanelContainer--> fireDone() wordt gestart");
        //Only open the frame when there are links.
        if(DomainController.getInstance().getLastPostTopicURLResults().size() > 0)
        {
            SwingUtilities.invokeLater(new Runnable()
            {
                public void run()
                {
                    LinksFrame lf = new LinksFrame();
                    lf.setLocationRelativeTo(null);
                    lf.setVisible(true);
                }
            });
        }
    }

    public boolean fireYesNoQuestion(String question, String title)
    {
    	System.out.println("PanelContainer--> fireYesNoQuestion() wordt gestart");
        return (JOptionPane.showConfirmDialog(this, question, title, JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION);
    }

    public void clearPost()
    {
    	System.out.println("PanelContainer--> clearPost() wordt gestart");
        this.postingPanel.clearPost();
    }

    public void loadHistoryItem(Post post)
    {
    	System.out.println("PanelContainer--> loadHistoryItem() wordt gestart");
        this.historyContainer.loadItem(post);
    }

    public void loadPost(Post post)
    {
    	
        this.postingPanel.loadPost(post);
        this.tabs.setSelectedIndex(0);
    }

    public void changeViewTo(View view)
    {
    	System.out.println("PanelContainer--> changeViewTo() wordt gestart");
        switch(view)
        {
        
            case POST:
            default:
                this.tabs.setSelectedIndex(0);
                break;
            case SETTINGS:
                this.tabs.setSelectedIndex(1);
                break;
            case HISTORY:
                this.tabs.setSelectedIndex(2);
                break;
            case LOG:
                this.tabs.setSelectedIndex(3);
                break;
            case ABOUT:
                this.tabs.setSelectedIndex(4);
                break;
        }System.out.println("PanelContainer--> switch --> changeViewTo() wordt gestart");
    }

    public void setPostBodyTo(String body)
    {
        this.postingPanel.setPostBodyTo(body);
    }

    public String getPost()
    {
        return this.postingPanel.getPost();
    }

    public void insertTagInPostBody(String tag)
    {
        this.postingPanel.insertTagInPostBody(tag);
    }

    public void updateForumUI()
    {
    	System.out.println("PanelContainer--> updateForumUI() wordt gestart");
        if(DomainController.getInstance().getForums().isViewUI())
        {
            getContentPane().add(this.forumQueuePane, java.awt.BorderLayout.LINE_START);
        }
        else
        {
            getContentPane().remove(this.forumQueuePane);
        }
        this.validate();
    }

    public String askCaptchaCode(String src)
    {
    	System.out.println("PanelContainer--> askCaptchaCode() wordt gestart");
        try
        {
            Icon icon = new ImageIcon(new URL(src));
            return (String) JOptionPane.showInputDialog(null, "Please enter the CAPTCHA code below.", "Enter CAPTCHA", JOptionPane.QUESTION_MESSAGE, icon, null, null);
        }
        catch(Exception ex)
        {
            DomainController.getInstance().getLogger().log(Level.WARNING, "Error while fetching the CAPTCHA image. {0}", ex.getMessage());
        }
        return null;
    }

    public void setStatusIndeterminate(boolean value, String status)
    {
    	System.out.println("PanelContainer--> setStatusIndeterminate() wordt gestart");
        this.statusPanel1.setStatusIndeterminate(value, status);
    }

    public String getSelectedTextInPost()
    {
    	System.out.println("PanelContainer--> getSelectedTextInPost() wordt gestart");
        return this.postingPanel.getSelectedTextInPost();
    }

    public void loadLookAndFeel()
    {
    	System.out.println("PanelContainer--> loadLookAndFeel() wordt gestart");
        this.settingsPanel.loadLookAndFeel();
    }

    public void setLookAndFeel(String className)
    {
        try
        {
            UIManager.setLookAndFeel(className);
        }
        catch(Exception e)
        {
            DomainController.getInstance().getLogger().log(Level.WARNING, "Can't change look and feel. {0}", e.getMessage());
        }
        finally
        {
            SwingUtilities.updateComponentTreeUI(this);
        }
    }

    public Post getCurrentPost()
    {
        return this.postingPanel.getCurrentPost();
    }

    public void updatePasswordUI()
    {
    	System.out.println("PanelContainer--> updatePasswordUI() wordt gestart");
        this.settingsPanel.updatePasswordUI();
    }

    public char[] askPassword(String text, String title)
    {
    	
    	System.out.println("PanelContainer--> askPassword() wordt gestart");
        JPasswordField passwordField = new JPasswordField();
        passwordField.setEchoChar('*');

        Object[] obj = {text + "\n\n", passwordField};
        Object stringArray[] = {"OK"};
        
        JOptionPane.showOptionDialog(null, obj, title, JOptionPane.YES_OPTION, JOptionPane.QUESTION_MESSAGE, null, stringArray, obj);

        return passwordField.getPassword();
    }

    public void loadQueue()
    {
    	System.out.println("PanelContainer--> loadQueue() wordt gestart");
        this.queuePanel1.loadQueue();
    }

    public String getSelectedQueueItem()
    {
        return this.queuePanel1.getSelectedQueueItem();
    }

    public void loadThreads()
    {
    	System.out.println("PanelContainer--> loadThreads() wordt gestart");
        this.settingsPanel.loadThreads();
    }

    public void addProgress(int i)
    {
    	System.out.println("PanelContainer--> addProgress() wordt gestart");
        this.statusPanel1.addProgress(i);
    }

    public void loadCoolDownPeriod()
    {
    	System.out.println("PanelContainer--> loadCoolDownPeriod() wordt gestart");
        this.settingsPanel.loadCoolDownPeriod();
    }

    public void loadRetry()
    {
        this.settingsPanel.loadRetry();
    }

    public void showPostingErrors()
    {
    	System.out.println("PanelContainer--> showPostingErrors() wordt gestart");
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                PostResultContainerFrame prcf = new PostResultContainerFrame();
                prcf.setLocationRelativeTo(null);
                prcf.setVisible(true);
            }
        });
    }

    public void showErrorAsHTML(String error)
    {
    	System.out.println("PanelContainer--> showErrorAsHTML() wordt gestart");
        PersistenceController.saveText(new File(Settings.TEMP_FILE), error);
        OpenBrowser.openURL("file://" + Settings.TEMP_FILE);
    }
}